package online.heycm.platform.common.tools.cipher.core;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import java.nio.charset.StandardCharsets;
import javax.crypto.SecretKey;

/**
 * AES对称加密
 *
 * @author heycm
 * @since 2023/11/19 19:04
 */
public class AESCore {

    private AESCore() {}

    /**
     * 加密
     *
     * @param key     秘钥
     * @param content 内容
     * @return
     */
    public static String encrypt(String key, String content) {
        AES aes = new AES(key.getBytes(StandardCharsets.UTF_8));
        return AESCore.encrypt(aes, content);
    }

    /**
     * 加密
     *
     * @param aes     AES实例
     * @param content 内容
     * @return
     */
    public static String encrypt(AES aes, String content) {
        return aes.encryptBase64(content);
    }

    /**
     * 解密
     *
     * @param key     秘钥
     * @param encrypt 密文
     * @return
     */
    public static String decrypt(String key, String encrypt) {
        AES aes = new AES(key.getBytes(StandardCharsets.UTF_8));
        return AESCore.decrypt(aes, encrypt);
    }

    /**
     * 解密
     *
     * @param aes     AES实例
     * @param encrypt 密文
     * @return
     */
    public static String decrypt(AES aes, String encrypt) {
        return aes.decryptStr(encrypt, CharsetUtil.CHARSET_UTF_8);
    }

    /**
     * 生成秘钥
     *
     * @return
     */
    public static SecretKey secretKey() {
        return SecureUtil.generateKey(SymmetricAlgorithm.AES.name());
    }

    /**
     * 生成秘钥
     *
     * @return
     */
    public static String generateKey() {
        SecretKey key = AESCore.secretKey();
        return Base64.encode(key.getEncoded());
    }

    /**
     * 创建AES实例
     *
     * @param key 秘钥
     * @return
     */
    public static AES aes(String key) {
        return new AES(key.getBytes(StandardCharsets.UTF_8));
    }
}
